package com.share.ai.alibaba.dashscope.config;

import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.chat.memory.InMemoryChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
public class AiConfig {
    //langchain4j是用{{}},springboot中是{}
    //chatClient.prompt().system(s->s.param("voice",voice)) 会把参数塞到里面去
    private static final String DEFAULT_PROMPT = "你是一个博学的智能聊天助手，请根据用户提问回答,以{voice}的语气回答";

    //构建jdbc存储
    //如果没有配置其他存储库，Spring AI默认自动装载 InMemoryChatMemoryRepository
    //依赖spring-ai-alibaba-starter-memory-jdbc
    @Bean
    public ChatMemoryRepository chatMemoryRepository(JdbcTemplate jdbcTemplate) {
        ChatMemoryRepository chatMemoryRepository = null;
    //使用jvm内存的方式
        chatMemoryRepository = new InMemoryChatMemoryRepository();

        //使用数据库的模式
//       chatMemoryRepository = MysqlChatMemoryRepository.mysqlBuilder()
//                .jdbcTemplate(jdbcTemplate)
//                .build();
        return chatMemoryRepository;
    }

    @Bean
    public ChatMemory chatMemory(ChatMemoryRepository chatMemoryRepository) {
        ChatMemory chatMemory = MessageWindowChatMemory.builder()
                .chatMemoryRepository(chatMemoryRepository)
                .maxMessages(30)//30条记录
                .build();
        return chatMemory;
    }

    @Bean
    public ChatClient chatClient(ChatClient.Builder builder,ChatMemory chatMemory) {
        ChatClient build = builder.defaultAdvisors()
                .defaultSystem(DEFAULT_PROMPT) //预设角色
                .defaultAdvisors(new SimpleLoggerAdvisor())// 实现 Logger 的 Advisor
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build()) //实现记忆
                .defaultOptions(DashScopeChatOptions.builder().withTopP(0.7).build())
                .build();
        return build;
    }
}
